﻿using System;
using System.Text.RegularExpressions;

namespace Common
{
    /// <summary>
    /// 一些共有的方法
    /// </summary>
    public class Helper
    {
        /// <summary>
        /// 中文数字转成阿拉伯数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int Foh(string str)
        {
            string e = "零一二三四五六七八九";
            string[] ew = { "十", "百", "千" };
            string[] ej = { "万", "亿" };

            int a = 0;
            if (str.IndexOf(ew[0], StringComparison.Ordinal) == 0)
                a = 10;
            str = Regex.Replace(str, e[0].ToString(), "");

            if (Regex.IsMatch(str, "([" + e + "])$"))
            {
                a += e.IndexOf(Regex.Match(str, "([" + e + "])$").Value[0]);
            }

            if (Regex.IsMatch(str, "([" + e + "])" + ew[0]))
            {
                a += e.IndexOf(Regex.Match(str, "([" + e + "])" + ew[0]).Value[0]) * 10;
            }

            if (Regex.IsMatch(str, "([" + e + "])" + ew[1]))
            {
                a += e.IndexOf(Regex.Match(str, "([" + e + "])" + ew[1]).Value[0]) * 100;
            }

            if (Regex.IsMatch(str, "([" + e + "])" + ew[2]))
            {
                a += e.IndexOf(Regex.Match(str, "([" + e + "])" + ew[2]).Value[0]) * 1000;
            }
            return a;
        }
        /// <summary>
        /// 把中文章节编号转换成数字编号
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int ConvertTitle(string str)
        {

            var match = Regex.Match(str, @"[0-9]\d*");
            if (match.Length > 0)
            {
                 return  Convert.ToInt32(match.Value);
            }
            int st1 = str.IndexOf("第", StringComparison.Ordinal);
            int ot1 = str.IndexOf("章", StringComparison.Ordinal);
            if (st1 >= 0 && ot1 > 0)
            {
                var substring = str.Substring(st1 + 1, ot1 - 1);
                return Helper.Foh(substring);
            }

            int st2 = str.IndexOf("第", StringComparison.Ordinal);
            int ot2 = str.IndexOf("节", StringComparison.Ordinal);
            if (st2 >= 0 && ot2 > 0)
            {
                var substring = str.Substring(st2 + 1, ot2 - 1);
                return Helper.Foh(substring);
            }
            return 0;
        }
    }
}
